﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Web.UI.WebControls;

namespace APMAWebConsole.PlanningPart
{
    public partial class Iterations : System.Web.UI.Page
    {
        private const string IterationsDataSourceKey = "IterationsDataSourceKey";
        private const string ProjectsListKey = "ProjectsListKey";
        private const string ReleasesListKey = "ReleasesListKey";
        private const string IsEditModeKey = "IsEditModeKey";
        private const string IsUpdateKey = "IsUpdateKey";
        private const string IsViewModeKey = "IsViewModeKey";
        private const string UserStoriesListKey = "UserStoriesListKey";

        public DataTable DataSource
        {
            get
            {
                return ViewState[IterationsDataSourceKey] != null
                           ? (DataTable)ViewState[IterationsDataSourceKey]
                           : (DataTable)(ViewState[IterationsDataSourceKey] = SiteMaster.Proxy.GetIterationsList());
            }

            set { ViewState[IterationsDataSourceKey] = value; }
        }

        public DataTable ProjectsList
        {
            get
            {
                return ViewState[ProjectsListKey] != null
                           ? (DataTable)ViewState[ProjectsListKey]
                           : (DataTable)(ViewState[ProjectsListKey] = SiteMaster.Proxy.GetProjectsList());
            }

            set { ViewState[ProjectsListKey] = value; }
        }

        public DataTable ReleasesList
        {
            get
            {
                return ViewState[ReleasesListKey] != null
                           ? (DataTable)ViewState[ReleasesListKey]
                           : (DataTable)(ViewState[ReleasesListKey] = SiteMaster.Proxy.GetReleasesList());
            }

            set { ViewState[ReleasesListKey] = value; }
        }

        private DataTable UserStoriesList
        {
            get
            {
                if (ViewState[UserStoriesListKey] != null)
                    return (DataTable)ViewState[UserStoriesListKey];

                var table = SiteMaster.Proxy.GetUserStoriesList();

                var expression = "Iteration_id <> " + DataSource.Rows[SelectedRow]["Id"];

                var foundRows = table.Select(expression);

                foreach (var dataRow in foundRows)
                    table.Rows.Remove(dataRow);

                ViewState[UserStoriesListKey] = table;

                return (DataTable)ViewState[UserStoriesListKey];
            }

            set { ViewState[UserStoriesListKey] = value; }
        }

        public bool IsEditMode
        {
            set { ViewState[IsEditModeKey] = value; }
            get { return ViewState[IsEditModeKey] != null && (bool) ViewState[IsEditModeKey]; }
        }

        public bool IsViewMode
        {
            set { ViewState[IsViewModeKey] = value; }
            get { return ViewState[IsViewModeKey] != null && (bool)ViewState[IsViewModeKey]; }
        }

        public bool IsUpdate
        {
            set { ViewState[IsUpdateKey] = value; }
            get { return ViewState[IsUpdateKey] != null && (bool)ViewState[IsUpdateKey]; }
        }

        private int SelectedRow
        {
            get
            {
                int selectedRow;
                var isSuccessfully = int.TryParse(txtSelectedIteration.Text, out selectedRow);

                if (isSuccessfully && selectedRow - 1 >= 0 && selectedRow - 1 < DataSource.Rows.Count 
                        && DataSource.Rows[selectedRow - 1] != null)
                    return selectedRow - 1;

                return -1;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.User.Identity.IsAuthenticated)
                Response.Redirect("~/Account/Login.aspx");
        }

        private void Rebind()
        {
            if (IsEditMode)
            {
                txtIterationId.Enabled = false;

                ddlIterationProjectId.Enabled = txtIterationStartDate.Enabled = txtIterationEndDate.Enabled =
                                                                                ddlIterationStateId.Enabled =
                                                                                txtIterationPlanEstimate.Enabled =
                                                                                ddlIterationReleaseId.Enabled =
                                                                                btnCreateUpdate.Visible = !IsViewMode;

                ddlIterationProjectId.Items.Clear();
                ddlIterationProjectId.DataValueField = "Id";
                ddlIterationProjectId.DataTextField = "Name";
                ddlIterationProjectId.DataSource = ProjectsList;
                ddlIterationProjectId.DataBind();
                ddlIterationProjectId.Items.Insert(0, new ListItem(String.Empty, String.Empty));

                ddlIterationReleaseId.Items.Clear();
                ddlIterationReleaseId.DataValueField = "Id";
                ddlIterationReleaseId.DataTextField = "Id";
                ddlIterationReleaseId.DataSource = ReleasesList;
                ddlIterationReleaseId.DataBind();
                ddlIterationReleaseId.Items.Insert(0, new ListItem(String.Empty, String.Empty));

                ddlIterationStateId.Items.Clear();
                ddlIterationStateId.DataValueField = "Id";
                ddlIterationStateId.DataTextField = "Name";
                ddlIterationStateId.Items.Insert(0, new ListItem(String.Empty, String.Empty));
                ddlIterationStateId.Items.Insert(1, new ListItem("Planning", "4"));
                ddlIterationStateId.Items.Insert(2, new ListItem("Committed", "5"));
                ddlIterationStateId.Items.Insert(3, new ListItem("Accepted", "6"));

                if (!IsUpdate)
                {
                    txtIterationId.Text = txtIterationPlanEstimate.Text = "";
                    ddlIterationProjectId.SelectedIndex = 0;
                    ddlIterationReleaseId.SelectedIndex = 0;
                    ddlIterationStateId.SelectedIndex = 0;
                }
                else
                {
                    var selectedRow = SelectedRow;

                    if (selectedRow == -1)
                        return;

                    txtIterationId.Text = DataSource.Rows[selectedRow]["Id"].ToString();
                    DateTime dateTimeParseValue;

                    var isParsed = DateTime.TryParse(DataSource.Rows[selectedRow]["Start_date"].ToString(), out dateTimeParseValue);
                    txtIterationStartDate.Text = isParsed ? dateTimeParseValue.ToShortDateString() : "";
                    isParsed = DateTime.TryParse(DataSource.Rows[selectedRow]["End_date"].ToString(), out dateTimeParseValue);
                    txtIterationEndDate.Text = isParsed ? dateTimeParseValue.ToShortDateString() : "";
                    txtIterationPlanEstimate.Text = DataSource.Rows[selectedRow]["Plan_estimate"].ToString();

                    ddlIterationProjectId.SelectedValue = DataSource.Rows[selectedRow]["Project_id"].ToString() != ""
                                                            ? DataSource.Rows[selectedRow]["Project_id"].ToString()
                                                            : null;

                    ddlIterationReleaseId.SelectedValue = DataSource.Rows[selectedRow]["Release_id"].ToString() != ""
                                                            ? DataSource.Rows[selectedRow]["Release_id"].ToString()
                                                            : null;

                    ddlIterationStateId.SelectedValue = DataSource.Rows[selectedRow]["State_id"].ToString() != ""
                                                            ? DataSource.Rows[selectedRow]["State_id"].ToString()
                                                            : null;
                }

                grdUserStories.Visible = IsViewMode;
                if (IsViewMode)
                {
                    grdUserStories.DataSource = UserStoriesList;
                    grdUserStories.DataBind();
                }
            }
            else
            {
                grdIterations.DataSource = DataSource;
                grdIterations.DataBind();
            }
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);

            divEditMode.Visible = IsEditMode;
            divIterationsGrid.Visible = !IsEditMode;

            btnAddIteration.Visible = !IsEditMode; 
            btnEditIteration.Visible =
                btnRemoveIteration.Visible = btnViewIteration.Visible = false;
            btnBackToList.Visible = IsEditMode;

            if (IsEditMode)
            {
                btnCreateUpdate.Text = IsUpdate ? "Update" : "Create";
            }

            Rebind();
        }

        protected void OnButtonCommand(object sender, CommandEventArgs e)
        {
            switch (e.CommandName)
            {
                case "Add":
                    {
                        IsEditMode = true;
                        IsUpdate = false;

                        break;
                    }
                case "Remove":
                    {
                        if (e.CommandArgument.ToString() != "")
                            txtSelectedIteration.Text = e.CommandArgument.ToString();

                        RemoveIteration();

                        break;
                    }
                case "Edit":
                    {
                        IsEditMode = true;
                        IsUpdate = true;
                        IsViewMode = false;

                        break;
                    }

                case "Select":
                    {
                        txtSelectedIteration.Text = e.CommandArgument.ToString();
                        IsEditMode = true;
                        IsUpdate = true;
                        IsViewMode = false;

                        break;
                    }

                case "View":
                    {
                        if (e.CommandArgument.ToString() != "")
                            txtSelectedIteration.Text = e.CommandArgument.ToString();

                        IsEditMode = true;
                        IsUpdate = true;
                        IsViewMode = true;
                        UserStoriesList = null;

                        break;
                    }

                case "SaveUpdate":
                    {
                        if (IsEditMode)
                        {
                            if (IsUpdate)
                            {
                                UpdateIteration();
                            }
                            else
                            {
                                SaveIteration();
                            }
                        }

                        break;
                    }

                case "BackToList":
                    {
                        IsEditMode = false;
                        UserStoriesList = null;

                        break;
                    }
            }
        }

        private Dictionary<string, object> PrepareParameters(Dictionary<string, object> parameters)
        {
            int intParseValue;

            var isParsed = int.TryParse(ddlIterationProjectId.SelectedValue, out intParseValue);
            parameters.Add("Project_id", isParsed ? (int?)intParseValue : null);

            parameters.Add("Start_date", txtIterationStartDate.Text);

            parameters.Add("End_date", txtIterationEndDate.Text);

            isParsed = int.TryParse(ddlIterationStateId.SelectedValue, out intParseValue);
            parameters.Add("State_id", isParsed ? (int?)intParseValue : null);

            isParsed = int.TryParse(txtIterationPlanEstimate.Text, out intParseValue);
            parameters.Add("Plan_estimate", isParsed ? (int?)intParseValue : null);

            isParsed = int.TryParse(ddlIterationReleaseId.SelectedValue, out intParseValue);
            parameters.Add("Release_id", isParsed ? (int?)intParseValue : null);

            return parameters;
        }

        private bool ValidateFields()
        {
            return Page.IsValid;
        }

        private void SaveIteration()
        {
            if (!ValidateFields())
                return;

            var parameters = PrepareParameters(new Dictionary<string, object>());

            SiteMaster.Proxy.AddNewIteration(parameters, Page.User.Identity.Name);

            IsEditMode = false;
            DataSource = null;
        }

        private void UpdateIteration()
        {
            if (!ValidateFields())
                return;

            var parameters = new Dictionary<string, object>();

            int intParseValue;
            var isParsed = int.TryParse(txtIterationId.Text, out intParseValue);

            if (!isParsed)
                return;

            parameters.Add("Id", intParseValue);

            parameters = PrepareParameters(parameters);

            SiteMaster.Proxy.UpdateIteration(parameters, Page.User.Identity.Name);

            IsEditMode = false;
            DataSource = null;
        }

        private void RemoveIteration()
        {
            var selectedRow = SelectedRow;

            if (selectedRow == -1)
                return;

            int intParseValue;
            var isParsed = int.TryParse(DataSource.Rows[selectedRow]["Id"].ToString(), out intParseValue);

            if (!isParsed)
                return;

            SiteMaster.Proxy.RemoveIteration(intParseValue, Page.User.Identity.Name);

            IsEditMode = false;
            DataSource = null;
        }
    }
}